package com.itheima.d6_tcp3;

import java.io.*;
import java.net.Socket;
import java.util.List;

public class ServerReaderThread extends Thread{
    private Socket socket;

    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        // 3、从socket通信管道中得到一个字节输入流。
        try {
            InputStream inputStream =  socket.getInputStream();
            //转换流，将字节流转换为字符流
            InputStreamReader isr = new InputStreamReader(inputStream);

            // 4、把原始的字节输入流包装成高效的输入流
            br = new BufferedReader(isr);
            while (true) {
                // 5、使用数据输入流读取客户端发送过来的消息
                String s = null;
                s = br.readLine();

                if(s == null){
                    break;
                }else {
//                    System.out.print(socket.getInetAddress().getHostName() + " (" + socket.getInetAddress().getHostName() + ") " + ": ");
                    System.out.println(socket.getInetAddress().getHostAddress() + ": " + s);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if(br != null){
                    br.close();
                }
                // 6、释放资源
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
